package com.supor.aiot.mine.ui.ips;

import android.graphics.Color;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.utils.Logc;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.base.BaseMVVMActivity;
import com.supor.aiot.common.base.NoViewModel;
import com.supor.aiot.common.entity.UserInfo;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.utils.BitmapUtil;
import com.supor.aiot.mine.R;
import com.supor.aiot.mine.databinding.ActivityIpsBinding;

import java.util.ArrayList;
import java.util.HashMap;

import androidx.core.content.res.ResourcesCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Lifecycle;
import io.reactivex.rxjava3.functions.Consumer;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2021, by het, ShenZhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: WishActivity <br>
 * 作者: lei <br>
 * 日期: 2021/8/31 <br>
 */
public class IpsActivity extends BaseMVVMActivity<NoViewModel, ActivityIpsBinding> implements View.OnClickListener {
    private String[] titles = new String[]{"创新提交", "我的"};
    private Fragment mCurrentFragment;
    private AddIpsFragment addIpsFragment;
    private IpsListFragment ipsListFragment;
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private int activeSize;
    private int normalSize;

    @Override
    protected int resourceId() {
        return R.layout.activity_ips;
    }

    @Override
    protected void initView() {
        super.initView();
        bindingView.toolbar.setIvLeftOnClickListener(v -> finish());
        bindingView.toolbar.setTvLeftOnClickListener(v -> finish());
        // bindingView.btnSave.setOnClickListener(this);
        bindingView.tvCheckState.setOnClickListener(this);
        bindingView.tvRecord.setOnClickListener(this);
        bindingView.tvRecordAccept.setOnClickListener(this);
        bindingView.tvRecord.setSelected(true);
        bindingView.tvRecord.setTypeface(Typeface.DEFAULT_BOLD);
        displayUser(GlobalDataCache.userInfo);
    }

    @Override
    protected void initData() {
        super.initData();
        activeSize = getResources().getDimensionPixelSize(R.dimen.sp_16);
        normalSize = getResources().getDimensionPixelSize(R.dimen.sp_16);
        addIpsFragment = AddIpsFragment.newInstance();
        fragments.add(addIpsFragment);
        ipsListFragment = IpsListFragment.newInstance();
        fragments.add(ipsListFragment);

        bindingView.tabLayout.addOnTabSelectedListener(changeCallback);

        View tabView = getLayoutInflater().inflate(R.layout.view_tab, null);

        TextView tvTab = tabView.findViewById(R.id.tv_tab);
        tvTab.setText(titles[0]);
        tvTab.setTextSize(TypedValue.COMPLEX_UNIT_PX, normalSize);
        bindingView.tabLayout.addTab(bindingView.tabLayout.newTab().setCustomView(tabView));
        tabView = getLayoutInflater().inflate(R.layout.view_tab, null);
        tvTab = tabView.findViewById(R.id.tv_tab);
        tvTab.setText(titles[1]);
        tvTab.setTextSize(TypedValue.COMPLEX_UNIT_PX, normalSize);
        bindingView.tabLayout.addTab(bindingView.tabLayout.newTab().setCustomView(tabView));

        bindingView.tabLayout.getTabAt(0).select();

        // HideIMEUtil.wrap(this);
        //
        // InputHandleUtil inputHandleUtil = new InputHandleUtil();
        // inputHandleUtil.handleInputView(findViewById(android.R.id.content), bindingView.nScrollView, bindingView.llBtn);

        RxBus3.getInstance().register(Constants.Tag.ADD_IPS, (Consumer<String>) s -> {
            Logc.e("onTabReselected: " + s);
            ipsListFragment.refresh();
            bindingView.tabLayout.getTabAt(1).select();
            setExpanded(true);
        }, this.getClass());

        setAvatorChange();

    }

    private void displayUser(UserInfo userInfo) {
        if (userInfo == null || TextUtils.isEmpty(userInfo.getFaceImage())) {
            BitmapUtil.loadLocal(this, R.mipmap.ic_default_head, bindingView.ivIcon);
        } else {
            String headUrl = userInfo.getFaceImage();
            if (!TextUtils.isEmpty(headUrl)) {
                if ("1".equalsIgnoreCase(headUrl)) {
                    bindingView.ivIcon.setImageResource(R.mipmap.ic_default_head1);
                } else if ("2".equalsIgnoreCase(headUrl)) {
                    bindingView.ivIcon.setImageResource(R.mipmap.ic_default_head2);
                } else if ("3".equalsIgnoreCase(headUrl)) {
                    bindingView.ivIcon.setImageResource(R.mipmap.ic_default_head3);
                } else if ("4".equalsIgnoreCase(headUrl)) {
                    bindingView.ivIcon.setImageResource(R.mipmap.ic_default_head4);
                } else {
                    BitmapUtil.loadUrl(this, headUrl, bindingView.ivIcon);
                }
            }
        }
    }

    private void setFragment(int index) {
        final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment nextFragment = fragments.get(index);
        if (mCurrentFragment == null) {
            ft.add(R.id.frame_layout, mCurrentFragment = nextFragment);
            ft.setMaxLifecycle(nextFragment, Lifecycle.State.RESUMED);
        } else {
            if (mCurrentFragment == nextFragment) {
                return;
            }
            if (nextFragment.isAdded()) {
                ft.hide(mCurrentFragment);
                ft.setMaxLifecycle(mCurrentFragment, Lifecycle.State.STARTED);
                ft.show(mCurrentFragment = nextFragment);
                ft.setMaxLifecycle(nextFragment, Lifecycle.State.RESUMED);
            } else {
                ft.hide(mCurrentFragment);
                ft.setMaxLifecycle(mCurrentFragment, Lifecycle.State.STARTED);
                ft.add(R.id.frame_layout, mCurrentFragment = nextFragment);
                ft.setMaxLifecycle(nextFragment, Lifecycle.State.RESUMED);
            }
        }
        ft.commitAllowingStateLoss();
    }

    private TabLayout.OnTabSelectedListener changeCallback = new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            if (tab.getPosition() == 0) {
                // bindingView.llBtn.setVisibility(View.VISIBLE);
                bindingView.llRecord.setVisibility(View.INVISIBLE);
            } else {
                // bindingView.llBtn.setVisibility(View.GONE);
                bindingView.llRecord.setVisibility(View.VISIBLE);
            }
            View tabView = tab.getCustomView();
            if (tabView == null) {
                return;
            }
            TextView tvTab = tabView.findViewById(R.id.tv_tab);
            tvTab.setTextColor(getResources().getColor(R.color.content_default));
            tvTab.setTextSize(TypedValue.COMPLEX_UNIT_PX, activeSize);
            tvTab.setTypeface(Typeface.DEFAULT_BOLD);
            ImageView ivBg = tabView.findViewById(R.id.iv_bg);
            ivBg.setVisibility(View.VISIBLE);

            setFragment(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            View tabView = tab.getCustomView();
            if (tabView == null) {
                return;
            }
            TextView tvTab = tabView.findViewById(R.id.tv_tab);
            tvTab.setTextColor(getResources().getColor(R.color.content_assist));
            tvTab.setTextSize(TypedValue.COMPLEX_UNIT_PX, normalSize);
            tvTab.setTypeface(Typeface.DEFAULT);

            ImageView ivBg = tabView.findViewById(R.id.iv_bg);
            ivBg.setVisibility(View.GONE);
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            Logc.i("onTabReselected: pos: " + tab.getPosition());
        }
    };

    /**
     * 渐变toolbar背景
     */
    private void setAvatorChange() {
        bindingView.appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                // Logc.e("onOffsetChanged: " + verticalOffset);
                //verticalOffset始终为0以下的负数
                float percent = (Math.abs(verticalOffset * 1.0f) / appBarLayout.getTotalScrollRange());

                bindingView.toolbar.setBackgroundColor((changeAlpha(0xFFF5F5F5, percent)));
            }
        });
    }

    /** 根据百分比改变颜色透明度 */
    public int changeAlpha(int color, float fraction) {
        int red = Color.red(color);
        int green = Color.green(color);
        int blue = Color.blue(color);
        int alpha = (int) (Color.alpha(color) * fraction);
        return Color.argb(alpha, red, green, blue);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_check_state){
            if (bindingView.clIpsTip.getVisibility() == View.GONE) {
                bindingView.clIpsTip.setVisibility(View.VISIBLE);
                bindingView.tvCheckState.setText(R.string.pack_up_state1);
                bindingView.tvCheckState.setCompoundDrawablesWithIntrinsicBounds(null, null,
                        ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_wish_up, null),
                        null);
            } else {
                bindingView.clIpsTip.setVisibility(View.GONE);
                bindingView.tvCheckState.setText(R.string.check_state1);
                bindingView.tvCheckState.setCompoundDrawablesWithIntrinsicBounds(null, null,
                        ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_wish_down, null),
                        null);
            }
        } else if (id == R.id.btn_save) {
            if (addIpsFragment != null) {
                addIpsFragment.click(v);
            }
        } else if (id == R.id.tv_record) {
            bindingView.tvRecord.setSelected(true);
            bindingView.tvRecord.setTypeface(Typeface.DEFAULT_BOLD);
            bindingView.tvRecordAccept.setSelected(false);
            bindingView.tvRecordAccept.setTypeface(Typeface.DEFAULT);
            if (ipsListFragment != null) {
                ipsListFragment.click(v);
            }
        } else if (id == R.id.tv_record_accept) {
            bindingView.tvRecord.setSelected(false);
            bindingView.tvRecord.setTypeface(Typeface.DEFAULT);
            bindingView.tvRecordAccept.setSelected(true);
            bindingView.tvRecordAccept.setTypeface(Typeface.DEFAULT_BOLD);
            if (ipsListFragment != null) {
                ipsListFragment.click(v);
            }
        }
    }

    public void updateNum(int num, int acceptNum) {
        bindingView.tvRecord.setText(getString(R.string.record) + " " + num);
        bindingView.tvRecordAccept.setText(getString(R.string.record_accept) + " " + acceptNum);
    }

    public void setExpanded(boolean expanded) {
        bindingView.appbar.setExpanded(expanded);
    }

    @Override
    public void updateNetStatus(int type) {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus3.getInstance().unregister(this.getClass());
    }

    public static final HashMap<String, Integer> idMap = new HashMap<>();

    static {
        idMap.put("E0", R.mipmap.device_rice_cooker);
        idMap.put("F0", R.mipmap.device_stewpot);
        idMap.put("SY-50MT01", R.mipmap.device_chef_machine01);
        idMap.put("SY-50MT10", R.mipmap.device_chef_machine10);
        idMap.put("A1", R.mipmap.device_pressure_cooker);
        idMap.put("A2", R.mipmap.device_fryer);
        idMap.put("A3", R.mipmap.device_air_fryer);
        idMap.put("A4", R.mipmap.device_air_oven);
        idMap.put("A5", R.mipmap.device_small_cooking_pot);
        idMap.put("MY85", R.mipmap.device_oven85);
        idMap.put("MY88", R.mipmap.device_oven88);
        idMap.put("C0", R.mipmap.device_broken_food_processor);
        idMap.put("C1", R.mipmap.device_radiant_cooker);
        idMap.put("C2", R.mipmap.device_food_processor);
        idMap.put("C3", R.mipmap.device_induction_cooker);
        idMap.put("C4", R.mipmap.device_soymilk_machine);
        idMap.put("C5", R.mipmap.device_juice_machine);
        idMap.put("C7", R.mipmap.device_mixer);
        idMap.put("C8", R.mipmap.device_egg_breaking);
        idMap.put("C9", R.mipmap.device_meat_grinder);
        idMap.put("CA", R.mipmap.device_baby_cook);
        idMap.put("CB", R.mipmap.device_tumbler);
        idMap.put("D0", R.mipmap.device_kettle);
        idMap.put("D1", R.mipmap.device_health_pot);
        idMap.put("D2", R.mipmap.device_health_cup);
        idMap.put("D3", R.mipmap.device_coffee_machine);
        idMap.put("D4", R.mipmap.device_toaster);
        idMap.put("Z", R.mipmap.ic_other_product_unselect);
    }
}
